<?php

namespace notification;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Exception\TeaError;
use Darabonba\OpenApi\Models\Config;
use think\facade\Env;
use AlibabaCloud\Dara\Models\RuntimeOptions;

class Sms
{
    public $client;

    public function __construct()
    {
        $config = new Config([
            "accessKeyId" => Env::get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
            "accessKeySecret" => Env::get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
            "endpoint" => "dysmsapi.aliyuncs.com",
            "protocol" => "https"
        ]);
        $this->client = new Dysmsapi($config);
    }

    public function send($phone, $code)
    {
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $phone,
            "signName" => "广东中翊能源",
            "templateCode" => "SMS_493235526",
            "templateParam" => json_encode([
                'code' => $code,
            ])
        ]);

        try {
            $result = $this->client->sendSmsWithOptions($sendSmsRequest, new RuntimeOptions([]));
            return [
                'success' => true,
                'message' => '短信发送成功',
                'data' => $result->toMap()
            ];
        } catch (\Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            return [
                'success' => false,
                'message' => $error->message,
                'data' => isset($error->data["Recommend"]) ? $error->data["Recommend"] : null
            ];
        }
    }
}
